/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aptech.servlet;

import aptech.container.Constants;
import aptech.data.ScheduleActivityBO;
import aptech.entities.ScheduleActivity;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.GregorianCalendar;

import java.util.List;

/**
 *
 * @author home
 */
@WebServlet(name = "ScheduleActivityServlet", urlPatterns = {"/ScheduleActivityServlet"})
public class ScheduleActivityServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            String action = request.getParameter(Constants.ACTION);
            ScheduleActivityBO schedule_bo = new ScheduleActivityBO();

            if (action.equals(Constants.ACTION_ADD)) {
                String title = request.getParameter(Constants.SCHEDULE_TITLE);
                String startdate = request.getParameter(Constants.SCHEDULE_STARTDATE);
                String enddate = request.getParameter(Constants.SCHEDULE_ENDDATE);
                String address = request.getParameter(Constants.SCHEDULE_ADDRESS_TAKEPLACE);
                String description = request.getParameter(Constants.SCHEDULE_DESCRIPTION);
                if (title == null) {
                    title = "title";
                }
                if (startdate == null) {
                    startdate = "2012/01/01 12:00:00";
                }
                if (enddate == null) {
                    enddate = "2012/01/01 12:00:00";
                }
                if (address == null) {
                    address = "address";
                }
                if (description == null) {
                    description = "description";
                }
                //set data
                ScheduleActivity schedule = new ScheduleActivity();
                schedule.setTitleScheduleActivity(title);
                schedule.setStartDateSchedule(startdate);
                schedule.setEndDateSchedule(enddate);
                schedule.setAddressTakePlace(address);
                schedule.setDescription(description);
                //add           
                boolean status = schedule_bo.addNew(schedule);

                if (status) {
                    //message + scheduleid
                    int id = schedule_bo.getAll().get(schedule_bo.getAll().size() - 1).getScheduleActivityId();

                    List<Date> list = fetchdates(new SimpleDateFormat("dd/MM/yyyy").parse(schedule.getStartDateSchedule()), new SimpleDateFormat("dd/MM/yyyy").parse(schedule.getEndDateSchedule()));
                    String allday = "";
                    if (list.size() == 0) {
                        allday = schedule.getStartDateSchedule();
                    }
                    for (int i = 0; i < list.size(); i++) {
                        if (i == list.size() - 1) {
                            allday += new SimpleDateFormat("dd/MM/yyyy").format(list.get(i));
                        } else {
                            allday += new SimpleDateFormat("dd/MM/yyyy").format(list.get(i)) + ",";
                        }
                    }
                    //ket qua
                    //id + allday
                    //<message>success</message>
                    out.println("<result><scheduleid>" + id + "</scheduleid><allday>" + allday + "</allday></result>");

                }
            }

            if (action.equals(Constants.ACTION_EDIT)) {
                String id = request.getParameter(Constants.SCHEDULE_ACTIVITY_ID);
                ScheduleActivity schedule = schedule_bo.getById(Integer.parseInt(id), true);

                if (schedule != null) {
                    String title = request.getParameter(Constants.SCHEDULE_TITLE);
                    String startdate = request.getParameter(Constants.SCHEDULE_STARTDATE);
                    String enddate = request.getParameter(Constants.SCHEDULE_ENDDATE);
                    String address = request.getParameter(Constants.SCHEDULE_ADDRESS_TAKEPLACE);
                    String description = request.getParameter(Constants.SCHEDULE_DESCRIPTION);
                    if (title == null) {
                        title = "title";
                    }
                    if (startdate == null) {
                        startdate = "2012/01/01 12:00:00";
                    }
                    if (enddate == null) {
                        enddate = "2012/01/01 12:00:00";
                    }
                    if (address == null) {
                        address = "address";
                    }
                    if (description == null) {
                        description = "description";
                    }
                    schedule.setTitleScheduleActivity(title);
                    schedule.setStartDateSchedule(startdate);
                    schedule.setEndDateSchedule(enddate);
                    schedule.setAddressTakePlace(address);
                    schedule.setDescription(description);
                    //edit
                    boolean status = schedule_bo.update(schedule);
                    if (status) {
                        out.println("<result>success</result>");
                    }
                }
            }

            if (action.equals(Constants.ACTION_DELETE)) {
                String id = request.getParameter(Constants.SCHEDULE_ACTIVITY_ID);
                ScheduleActivity schedule = schedule_bo.getById(Integer.parseInt(id), true);
                boolean status = schedule_bo.delete(schedule);
                if (status) {
                    out.println("<result>success</result>");
                }
            }
        } catch (Exception ex) {
            out.println("<result>error</result>");
            ex.printStackTrace();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    private List<Date> fetchdates(Date fechaInicial, Date fechaFinal) {
        List<Date> dates = new ArrayList<Date>();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(fechaInicial);
        Calendar cal = Calendar.getInstance();
        cal.setTime(fechaFinal);
        cal.add(Calendar.DATE, 1);
        while (calendar.getTime().before(cal.getTime())) {
            Date resultado = calendar.getTime();
            dates.add(resultado);
            calendar.add(Calendar.DATE, 1);
        }
        return dates;
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
